<template>
  <div class="create-page">
    <!-- 面包屑 -->
    <div class="breadcrumb">工作协同 / 软件列表 / 添加软件</div>

    <!-- 步骤指示 -->
    <div class="steps">
      <div :class="['step', step===1 ? 'active' : '']">
        <div class="num">1</div>
        <div class="label">选择基础信息</div>
        <div class="sub">创建软件信息</div>
      </div>
      <div :class="['step', step===2 ? 'active' : '']">
        <div class="num">2</div>
        <div class="label">上传软件和文件</div>
        <div class="sub">上传软件的相关文文件</div>
      </div>
      <div :class="['step', step===3 ? 'active' : '']">
        <div class="num">3</div>
        <div class="label">上传软件和教程</div>
        <div class="sub">上传软件的相关文文件</div>
      </div>
    </div>

    <!-- 主体内容区 -->
    <div class="content">
      <!-- 左下角插画占位 -->
      <img class="corner-illu" :src="softManImg" alt="corner" @error="hide" />

      <!-- Step 1: 基础信息 -->
      <div v-if="step===1" class="form-card">
        <el-form :model="form" label-width="100px" class="base-form">
          <el-form-item label="软件名称" required>
            <el-input v-model="form.name" placeholder="请输入" />
          </el-form-item>
          <el-form-item label="软件类型" required>
            <el-select v-model="form.category" placeholder="全部">
              <el-option label="全部" value="" />
              <el-option label="视频剪辑" value="视频剪辑" />
              <el-option label="图文编辑" value="图文编辑" />
              <el-option label="文案工具" value="文案工具" />
              <el-option label="其他工具" value="其他工具" />
            </el-select>
          </el-form-item>
          <el-form-item label="上线状态" required>
            <el-select v-model="form.status" placeholder="全部">
              <el-option label="全部" value="" />
              <el-option label="已上线" value="已上线" />
              <el-option label="待上线" value="待上线" />
            </el-select>
          </el-form-item>
          <el-form-item label="软件图标">
            <el-upload
              class="icon-upload"
              drag
              :auto-upload="true"
              :action="uploadAction"
              name="file"
              :show-file-list="false"
              :headers="uploadHeaders"
              :with-credentials="false"
              accept="image/*"
              :on-success="onIconUploaded"
              :on-error="onUploadError"
            >
              <el-icon><Upload /></el-icon>
              <div class="el-upload__text">
                拖拽到此处，或点击上传图标
              </div>
            </el-upload>
          </el-form-item>
          <el-form-item label="软件说明">
            <el-input v-model="form.desc" type="textarea" placeholder="请输入" />
          </el-form-item>
        </el-form>
      </div>

      <!-- Step 2: 上传文件（支持多个文件） -->
      <div v-if="step===2" class="upload-card">
        <div v-if="files.length===0" class="empty-upload">
          <img class="empty-illu" :src="softEmptyImg" alt="空" @error="hide" />
          <div class="empty-text">文件夹为空</div>
          <el-button type="primary" @click="openUpload">开始上传</el-button>
        </div>
        <div v-else class="files-wrap">
          <el-table :data="files" border>
            <el-table-column type="index" label="#" width="60" />
            <el-table-column prop="name" label="文件名" />
            <el-table-column prop="size" label="大小" width="120" />
            <el-table-column prop="type" label="类型" width="140" />
            <el-table-column label="操作" width="120">
              <template #default="scope">
                <el-button type="danger" link @click="removeFile(scope.$index)">移除</el-button>
              </template>
            </el-table-column>
          </el-table>
          <div class="upload-actions">
            <el-button @click="openUpload">继续添加文件</el-button>
          </div>
        </div>
      </div>

      <!-- Step 3: 完成与说明 -->
      <div v-if="step===3" class="done-card">
        <img class="done-illu" :src="softDoneImg" alt="完成" @error="hide" />
        <div class="done-actions">
          <el-button @click="backToList">返回列表</el-button>
          <el-button type="primary" @click="restart">再次创建</el-button>
        </div>

        <el-card class="note" shadow="never">
          <div class="note-title">表单说明</div>
          <div class="note-body">
            该软件仅供社团自研软件使用，部分法律法规、信息披露严格，文件上传完善后需复核，最新规则以社团政策为准，
            <a href="javascript:void(0)">查看详情</a>
          </div>
        </el-card>
      </div>
    </div>

    <!-- 底部操作区 -->
    <div class="footer-actions">
      <el-button @click="backToList">返回列表</el-button>
      <el-button type="primary" @click="next">下一步</el-button>
    </div>

    <!-- 上传弹窗占位 -->
    <el-dialog v-model="uploadDialog" title="上传文件" width="720px">
      <div class="dialog-content">
        <img class="dialog-illu" :src="softUploadImg" alt="上传占位" @error="hide" />
        <div class="dialog-text">
          将文件拖到此处，或
          <a href="javascript:void(0)" @click="pick">点击上传</a>
        </div>

        <el-upload
          ref="uploadRef"
          drag
          :action="uploadAction"
          name="file"
          :auto-upload="true"
          multiple
          :headers="uploadHeaders"
          :with-credentials="false"
          :on-success="onFileUploaded"
          :on-error="onUploadError"
        >
          <el-icon><Upload /></el-icon>
          <div class="el-upload__text">拖拽或点击添加文件（占位，不实际上传）</div>
        </el-upload>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="uploadDialog=false">取消</el-button>
          <el-button type="primary" @click="uploadDialog=false">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed } from 'vue'
import api from '../api'
import { Upload } from '@element-plus/icons-vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import softManImg from '../assets/SoftMan.png'
import softEmptyImg from '../assets/SoftEmpty.png'
import softDoneImg from '../assets/SoftDone.png'
import softUploadImg from '../assets/SoftUpload.png'

const router = useRouter()
const uploadAction = computed(() => {
  const baseURL = api.defaults.baseURL?.replace(/\/$/, '') || 
                  (import.meta.env.MODE === 'production' ? '' : 'http://drive.kbin.cc:3000')
  return baseURL + '/api/upload'
})
const uploadHeaders = computed(() => {
  const t = localStorage.getItem('token')
  return t ? ({ Authorization: `Bearer ${t}` }) : ({})
})

const step = ref(1)
const form = ref({
  name: '',
  category: '',
  status: '',
  desc: '',
  icon: null
})
const files = ref([])
const softwareId = ref(null)
const creating = ref(false)

const uploadDialog = ref(false)
const uploadRef = ref()

async function next(){
  if (step.value === 1) {
    step.value = 2
  } else if (step.value === 2) {
    await submitSoftware()
    step.value = 3
  } else {
    step.value = 1
  }
}
function backToList(){
  router.push('/collab/software')
}
function restart(){
  step.value = 1
  form.value = { name:'', category:'', status:'', desc:'', icon:null }
  files.value = []
}
function openUpload(){ uploadDialog.value = true }
function pick(){ /* 仅占位 */ }

// 图标上传成功（后端返回 { filePath, fileSize }）
function onIconUploaded(resp, file){
  const path = resp?.data?.filePath || resp?.filePath || resp?.data?.path || (file?.response?.data?.filePath) || ''
  form.value.icon = path || file?.name || null
}

// 文件上传成功（采集真实路径与字节大小）
function onFileUploaded(resp, file){
  const path = resp?.data?.filePath || resp?.filePath || resp?.data?.path || ''
  const sizeBytes = resp?.data?.fileSize || resp?.fileSize || file?.size || file?.raw?.size || 0
  files.value.push({
    name: file?.name || '未命名文件',
    size: sizeBytes ? (Math.round(sizeBytes/1024/1024*10)/10)+'MB' : '—',
    sizeBytes,
    type: file?.raw?.type || '—',
    path
  })
  uploadDialog.value = false
}

// 提交软件与文件到后端
async function submitSoftware(){
  creating.value = true
  try{
    // 创建软件
    const payload = {
      name: form.value.name || '未命名软件',
      category: form.value.category || '',
      status: form.value.status || '已上线',
      description: form.value.desc || '',
      icon_url: form.value.icon || undefined
    }
    const resp = await api.post('/api/software', payload)
    const id = resp?.data?.data?.id ?? resp?.data?.id
    softwareId.value = id

    // 逐个添加文件（占位路径与字节大小换算）
    for (const f of files.value) {
      const sizeBytes = typeof f.size === 'string' && f.size.endsWith('MB')
        ? Math.round(parseFloat(f.size) * 1024 * 1024)
        : 0
      await api.post(`/api/software/${id}/files`, {
        file_name: f.name,
        file_path: f.path || `/uploads/${f.name}`,
        file_size: f.sizeBytes ?? sizeBytes,
        file_type: f.type || ''
      })
    }
  } finally{
    creating.value = false
  }
}
function addFile(file){
  // 将选择的文件添加到列表中，占位显示
  files.value.push({
    name: file.name || '未命名文件',
    size: (file.size ? (Math.round(file.size/1024/1024*10)/10)+'MB' : '—'),
    type: file.raw ? file.raw.type || '—' : '—'
  })
}
function removeFile(i){ files.value.splice(i,1) }
function onIconChange(file){ form.value.icon = file.name }
function onUploadError(err){
  const msg = err?.response?.data?.message || err?.message || '上传失败'
  ElMessage.error(msg)
}
function hide(e){ e.target.style.opacity = 0 }
</script>

<style scoped>
.create-page{ padding: 14px; }

/* 面包屑 */
.breadcrumb{ color:#8a8a8a; font-size:12px; margin-bottom:8px; }

/* 步骤指示 */
.steps{
  display:flex; justify-content:center; gap:140px; margin:16px 0 24px;
}
.step{ text-align:center; color:#8a8a8a; }
.step .num{
  width:28px; height:28px; border-radius:50%;
  background:#3A78FF; color:#fff; display:inline-flex; align-items:center; justify-content:center;
  margin:0 auto 8px;
}
.step .label{ font-size:14px; color:#333; font-weight:600; }
.step .sub{ font-size:12px; color:#8a8a8a; }
.step.active .num{ background:#409EFF; }

/* 内容区 */
.content{ position:relative; min-height:360px; }
.corner-illu{
  position:absolute; left:48px; bottom:-12px; width:160px; height:auto; object-fit:contain;
}

/* 卡片与表单 */
.form-card, .upload-card, .done-card{
  display:flex; flex-direction:column; align-items:center; justify-content:center;
}
.base-form{
  width:640px; padding:12px; background:#f8fafc; border-radius:8px;
}
.icon-upload{ width:100%; }

/* 上传空状态 */
.empty-upload{
  display:flex; flex-direction:column; align-items:center; justify-content:center;
}
.empty-illu{ width:320px; max-width:60vw; height:auto; object-fit:contain; margin-bottom:8px; }
.empty-text{ color:#8a8a8a; margin-bottom:12px; }

/* 文件列表 */
.files-wrap{ width:820px; }
.upload-actions{ display:flex; justify-content:flex-end; gap:10px; margin-top:10px; }

/* 完成页 */
.done-illu{ width:360px; max-width:70vw; height:auto; object-fit:contain; margin-bottom:12px; }
.done-actions{ display:flex; gap:10px; justify-content:center; margin-bottom:16px; }
.note{ width:820px; }
.note-title{ font-weight:700; margin-bottom:6px; }
.note-body{ color:#666; }

/* 底部操作区 */
.footer-actions{
  display:flex; justify-content:flex-end; gap:10px; margin-top:24px;
}
</style>